#include"MyString.h"

ostream& operator<<(ostream& out, MyString& str)
{
	int len = str.size();
	for (int i = 0; i < len; i++)
		printf("%c", str[i]);
	return out;
}

istream& operator>>(istream& in, MyString& str)
{
	char ch;
	str.Msize = 0;
	str.Mcapacity = 4;

	while ((ch = getchar()) != '\n')
		str += ch;

	//while ((ch=getchar())!='\n')
	//{
	//	if (str.Mcapacity == str.Msize)
	//	{
	//		str.Mcapacity *= 2;
	//		MyString tem = str;
	//		//cout << str << endl;

	//		str.Mstr = new char[sizeof(char) * str.Mcapacity];
	//		memcpy(str.Mstr, tem.Mstr, sizeof(char)*tem.Msize);
	//	}
	//	//要先开空间，在填入数据
	//	//最好不要先自增Msize
	//	//先自增会拷贝来一个任意字符

	//	//后开空间会更安全
	//	str.Mstr[str.Msize++] = ch;
	//}

	return in;
}

int MyString::size()
{
	return Msize;//实际空间
}
int MyString::length()
{
	return Msize;
}

char MyString::operator[](const int pos)
{
	return this->Mstr[pos];
}

void MyString::operator=(const MyString& other)
{
	Mcapacity = other.Mcapacity;
	Msize = other.Msize;
	Mstr = new char[sizeof(char) * Mcapacity];
	memcpy(Mstr, other.Mstr, sizeof(char) * Msize);
}

MyString MyString::operator+(const MyString& other)
{
	MyString a(other.Mstr);
	return a;
}

MyString& MyString::operator+=(const MyString& other)
{
	//cout << other.Mstr << endl;
	*this += other.Mstr;
	return *this;
}
MyString& MyString::operator+=(const char ch)
{
	if (this->Mcapacity == this->Msize)
	{
		this->Mcapacity *= 2;
		MyString tem = *this;

		this->Mstr = new char[sizeof(char) * this->Mcapacity];
		memcpy(this->Mstr, tem.Mstr, sizeof(char) * tem.Msize);
	}
	this->Mstr[this->Msize++] = ch;

	//	//要先开空间，在填入数据
	//	//最好不要先自增Msize
	//	//先自增会拷贝来一个任意字符

	//	//后开空间会更安全

	return *this;
}

MyString& MyString::operator+=(const char* str)
{
	//使用字符数组进行拼接更有效率
	int len = strlen(str);
	//cout << len << endl;
	while (this->Mcapacity <= len + this->Msize)
	{
		this->Mcapacity *= 2;
		MyString tem = *this;

		this->Mstr = new char[sizeof(char) * this->Mcapacity];
		memcpy(this->Mstr, tem.Mstr, sizeof(char) * tem.Msize);
	}
	int size = this->Msize;
	//要学会调用系统库
	memcpy(this->Mstr+this->Msize, str, sizeof(char) * len);
	this->Msize += len;

	//for (int j=0; this->Msize < len + size; this->Msize++,j++)
	//	this->Mstr[this->Msize] = str[j];

	return *this;
}